package com.zheng.security.service.impl;

import com.zheng.security.exception.ApiException;
import com.zheng.security.service.UserService;
import com.zheng.security.utils.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @author zyq
 * @Description
 * @createTime 2021年01月15日 17:39:00
 */
@Service
public class UserServiceImpl implements UserService {

    private final UserDetailsService userDetailsService;
    private final BCryptPasswordEncoder passwordEncoder;
    private final JwtUtil jwtUtil;

    public UserServiceImpl(UserDetailsService userDetailsService, BCryptPasswordEncoder passwordEncoder, JwtUtil jwtUtil) {
        this.userDetailsService = userDetailsService;
        this.passwordEncoder = passwordEncoder;
        this.jwtUtil = jwtUtil;
    }


    @Override
    public String login(String username, String password) {
        //判断用户名或密码是否为空
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)){
            throw new ApiException("用户名或密码为空");
        }

        //根据用户名获取用户信息并判断密码是否正确
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if (!passwordEncoder.matches(password, userDetails.getPassword())) {
            throw new ApiException("密码不正确");
        }
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);
        //验证成功返回token
        return jwtUtil.generateToken(userDetails);
    }
}
